"""
本算法通过先输入的两组对应的电流和有效功率数组拟合两者之间的线性函数关系，
之后再将新输入的一组电流和有效功率数据与之前求得的线性函数进行比对计算点到函数直线的距离，求出该数据的线性偏离度。
"""
from ctypes import c_float
import math
import pandas as pd

def deviation_calculation(Irms, power, new_Irms, new_power):
    sumIrms = sum(Irms)
    sumPower = sum(power)
    sumIrmsPower = sum(i * p for i, p in zip(Irms, power))
    sumIrms2 = sum(i * i for i in Irms)
    slope = (50 * sumIrmsPower - sumIrms * sumPower) / (50 * sumIrms2 - sumIrms * sumIrms)
    intercept = (sumPower - slope * sumIrms) / 50
    distribution = abs(slope * new_Irms - new_power + intercept) / math.sqrt(slope * slope + 1)
    return distribution


def deviation_calculation_route(data_path):
    suffix = data_path.split(".")[1]

    #先获取原数组
    power = []
    Irms = []
    with open("input_deviation_calculation_Array.txt", "r", encoding='utf-8') as file:
        for line in file:
            if line.startswith("Irms:") and line.count(';') == 1:
                # 筛选并存储算法输入数据
                parts = line.strip().split(';')
                Irms.append(float(parts[0].split(':')[1]))
                power.append(float(parts[1].split(':')[1]))
    # 将Python中的列表转换为C语言中的数组
    Irms_array = (c_float * len(Irms))(*Irms)
    power_array = (c_float * len(power))(*power)


    #获取新数组
    # 如果输入文件是xlsx格式的。
    if suffix == "xlsx":
        data = pd.read_excel(data_path)
        for i in range(len(data)):
            # 新的数组
            new_Irms = data.iloc[i,0]
            new_power = data.iloc[i,1]
        d = deviation_calculation(Irms_array, power_array, new_Irms, new_power)
        # 输出算法结果
        d = round(d,2)
        result = [[{'线性偏离度': d}]]
        return result



    #如果输入文件是txt格式的。
    if suffix == "txt":
        with open(data_path, "r", encoding='utf-8') as file:
            for line in file:
                if line.startswith("Irms:") and line.count(';') == 1:
                    # 筛选并存储算法输入数据
                    parts = line.strip().split(';')
                    #新的数组
                    new_Irms = float(parts[0].split(':')[1])
                    new_power = float(parts[1].split(':')[1])

        # 调用算法
        d = deviation_calculation(Irms_array, power_array, new_Irms, new_power)
        # 输出算法结果
        d = round(d, 2)
        result = [[{'线性偏离度': d}]]
        return result

if __name__ == "__main__":
    # 读取文件路径
    data_path = 'input_deviation_calculation_newdata.xlsx'
    # data_path = 'input_deviation_calculation_newdata.xlsx'
    d = deviation_calculation_route(data_path)

    # d: 计算得到的线性偏离度。
    print('deviation:', d)



